
import os
import time
import logging

import rpyc
from rpyc.utils import server

import dexen
from dexen.system.base import service
from dexen.system.base.spec import DexenSpec
from dexen.system.server.job_manager import JobManager
import sys
#===============================================================================
# Constants
#===============================================================================
TASK_DIRNAME = "tasks"

#===============================================================================
# Globals
#===============================================================================
job_mgr = None

#===============================================================================
# The Service Class
#===============================================================================
class NodeManagerService(dexen.Service):
    ALIASES = ["NODE_MANAGER"]

    def on_connect(self):
        pass
    
    def on_disconnect(self):
        pass
    
    def run_schema(self, spec):
        assert isinstance(spec, DexenSpec)
        spec = rpyc.classic.obtain(spec)
        #print "the len schema zip", len(spec.schema_zip), type(spec.schema_zip)
        job_mgr.run_master(spec)

    

def main():
    global job_mgr, reg_addr
    try:
        logging.basicConfig(level=logging.DEBUG)
        
        ip_addr = service.get_my_ip_addr()
        
        svr = server.ThreadedServer(service=NodeManagerService, 
                                    protocol_config=service.default_config)
        
        #print "I am printing the ip and port", ip_addr, svr.port
        
        conn = rpyc.connect(sys.argv[1], service.REGISTRY_PORT)
        conn.root.register_node_mgr(None, (ip_addr, svr.port))
        
        reg_addr = sys.argv[1], service.REGISTRY_PORT
        
        job_mgr = JobManager(reg_addr)
        job_mgr.start()
        svr.start()     
    finally:
        pass
    
if __name__ == '__main__':
    main()

